<script lang="ts" setup>
  import { useVbenModal } from '@vben/common-ui';
  import { Gtable } from '../../../component';
  import operation from './../../../component/batch/operation.vue';
  import { v4 as uuidv4 } from 'uuid';
  import { defineProps, ref, computed } from 'vue';
  import type { ActionProp, BatchConfig, ConditionConf, GTableConfig } from '../../../utils/declar';
  import { getPageList } from "#/api";

  const props = defineProps({
    queryData: Object as PropType<ConditionConf>,
  });

  const uuid = ref("");
  const batchConfigData = ref<BatchConfig>({
    className: "com.gumo.entity.TypeField", // 类名
    displayAddButton: false, // 隐藏“添加”按钮
    tableData: [],
    addToSubmit: {},
  });

  const [Modal, modalApi] = useVbenModal({
    draggable: true,
    footer: false,
    onOpenChange: onOpenChange,
  });

  function onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      uuid.value = uuidv4(); // 仅在实际需要时更新UUID
    }
  }

  const extractAttrList = ({ records = [] }) =>
    records.map(({ attrList = [] }) =>
      attrList.reduce((obj, { attrName, value }) => {
        obj[attrName] = value;
        return obj;
      }, {})
    );

  const customTopAction: ActionProp[] = [
    {
      icon: "string",
      name: "批量修改",
      actionType: "top",
      dataValidation: false,
      key: "batchEdit",
      disabled: false,
      handler: async function () {
        try {
          console.log("查询参数:", props.queryData);
          const res = await getPageList({
            typeName: 'com.gumo.entity.TypeField',
            pageIndex: 1,
            pageSize: 999,
            conditions: props.queryData.value,
          });

          if (!res || !res.records) {
            console.warn("查询结果为空:", res);
            return;
          }

          batchConfigData.value.tableData = extractAttrList(res);
          modalApi.open();
        } catch (error) {
          console.error("获取数据失败:", error);
        }
      },
    },
  ];

  const tableConfig = computed<GTableConfig>(() => ({
    customType: 'add',
    customTopActions: customTopAction,
    queryData: props.queryData.value, // 保证 queryData 变更时更新配置
    className: "com.gumo.entity.TypeField",
    actionApiGet: false,
    isTree: false,
  }));
</script>

<template>
  <Modal class="w-[70vw]" title="属性修改">
    <operation :data="batchConfigData" />
  </Modal>
  <Gtable :config="tableConfig" />
</template>
